/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.common.utils.web.model;

import java.util.Iterator;
import java.util.List;

import com.google.common.collect.Lists;

/**
 * xxx
 *
 * @author Wangyi
 * @version v1.0
 *
 * @date 2013-9-18
 *
 */
public class SelectBoxModel implements Iterable<SelectBoxModel.Option>{
	
	private final List<Option> options = Lists.newArrayList();
	
	public SelectBoxModel addOption(String key, String value){
		this.options.add(new Option(key, value));
		return this;
	}
	
	public SelectBoxModel addOption(String key, String value, boolean selected){
		this.options.add(new Option(key, value, selected));
		return this;
	}
	
	public Option getOption(String key){
		return this.findOptionByKey(key);
	}
	
	public SelectBoxModel removeOption(String key){
		Option op=this.findOptionByKey(key);
		if(op!=null){
			this.options.remove(op);
		}
		return this;
	}
	
	public SelectBoxModel setFirstOptionSelected(){
		if(this.options.isEmpty()){
			return this;
		}
		Option prevSelected=null, nextSelected=this.options.get(0);		
		for(Option op : this.options){
			if(op.selected){
				prevSelected=op;
				break;
			}
		}
		if(prevSelected!=null && nextSelected!=null && prevSelected!=nextSelected){
			prevSelected.selected=false;
			nextSelected.selected=true;
		}
		return this;
	}
	
	public SelectBoxModel setOptionSelected(String key){
		Option prevSelected=null, nextSelected=null;
		for(Option op : this.options){
			if(op.selected){
				if(op.key.equals(key)){
					return this;
				}
				prevSelected=op;
			}
			if(op.key.equals(key)){
				nextSelected=op;
			}
		}
		if(prevSelected!=null){
			prevSelected.selected=false;
		}
		if(nextSelected!=null){
			nextSelected.selected=true;
		}
		return this;
	}
	
	private Option findOptionByKey(String key){
		for(Option op : this.options){
			if(op.key.equals(key)){
				return op;
			}
		}
		return null;
	}
	
	public SelectBoxModel clearOptions(){
		this.options.clear();
		return this;
	}
	
	/* (non-Javadoc)
	 * @see java.lang.Iterable#iterator()
	 */
	@Override
	public Iterator<Option> iterator() {
		return this.options.iterator();
	}

	public static class Option{
		public String key;
		public String value;
		public boolean selected;
		
		public Option(String key, String value){
			this.key=key;
			this.value=value;
		}
		
		public Option(String key, String value, boolean selected){
			this.key=key;
			this.value=value;
			this.selected=selected;
		}
	}

	/**
	 * @return the options
	 */
	public List<Option> getOptions() {
		return options;
	}
}
